<?php

namespace App\Exceptions;

use App\Exceptions\BusinessException;
use App\Exceptions\ValidationException;
use App\Traits\ApiResponse;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException as LaravelValidationException;
use Throwable;

class Handler extends ExceptionHandler
{
    use ApiResponse;

    /**
     * The list of the inputs that are never flashed to the session on validation exceptions.
     *
     * @var array<int, string>
     */
    protected $dontFlash = [
        'current_password',
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     */
    public function register(): void
    {
        $this->reportable(function (Throwable $e) {
            //
        });
    }

    /**
     * Render an exception into an HTTP response.
     */
    public function render($request, Throwable $e)
    {
        if ($request->expectsJson()) {
            return $this->handleApiException($request, $e);
        }

        return parent::render($request, $e);
    }

    /**
     * Convert an authentication exception into a response.
     */
    protected function unauthenticated($request, AuthenticationException $exception)
    {
        // 对于API请求，返回JSON响应
        if ($request->expectsJson() || $request->is('api/*')) {
            return $this->error('未授权访问', 401);
        }
        
        // 对于管理后台请求，重定向到登录页面
        if ($request->is('admin/*')) {
            return redirect()->route('admin.login');
        }
        
        // 对于其他web请求，重定向到管理后台登录页面
        return redirect()->route('admin.login');
    }

    /**
     * Handle API exceptions
     */
    protected function handleApiException(Request $request, Throwable $e): JsonResponse
    {
        if ($e instanceof AuthenticationException) {
            return $this->error('未授权访问', 401);
        }

        if ($e instanceof BusinessException) {
            return $this->error($e->getMessage(), $e->getBusinessCode(), $e->getErrors());
        }

        if ($e instanceof ValidationException) {
            return $this->error($e->getMessage(), 422, $e->getErrors());
        }

        if ($e instanceof LaravelValidationException) {
            return $this->error('数据验证失败', 422, $e->errors());
        }

        // 其他异常
        return $this->error('服务器内部错误', 50001);
    }
}
